package com.wanghua.spring.filter;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/*
* XSLT 转换 Filter。
* 该 Filter 可以利用 XSLT 样式文件将 XML 文件转换为其他格式。
* 大家都知道，MSN 的聊天记录是以 XML 格式文件形式保存的，本例使用 MSN 的 xsl 文件转换 MSN 聊天记录。
* */
public class XSLTFilter implements Filter {
	private ServletContext servletContext;

	public void init(FilterConfig config) throws ServletException {
		servletContext = config.getServletContext();
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		// 格式样本文件
		Source styleSource = new StreamSource(servletContext.getRealPath("/filter/msn/MessageLog.xsl"));

		// 请求的 xml 文件
		Source xmlSource = new StreamSource(servletContext.getRealPath(request.getRequestURI().replace(request.getContextPath() + "", "")));  //request.getRequestURI() 的值为“/filter/msn/demo.xml”；request.getContextPath() 的值为空字符串
		try {
			// 转换器工厂
			TransformerFactory transformerFactory = TransformerFactory.newInstance();

			// 转换器
			Transformer transformer = null;
			try {
				transformer = transformerFactory.newTransformer(styleSource);  //如果路径中有中文，执行会报错：无法编译样式表
			} catch (Throwable e) {
				String msg = e.getMessage();
			}
			// 将转换的结果保存到该对象中
			CharArrayWriter charArrayWriter = new CharArrayWriter();
			StreamResult result = new StreamResult(charArrayWriter);

			// 转换
			transformer.transform(xmlSource, result);

			// 输出转换后的结果
			response.setContentType("text/html");
			response.setContentLength(charArrayWriter.toString().length());
			PrintWriter out = response.getWriter();
			out.write(charArrayWriter.toString());

		} catch (Exception ex) {
		}
	}

	public void destroy() {
	}
}
